import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:interrogation/app/routes/app_pages.dart';
import 'package:interrogation/src/data/api.dart';
import 'package:interrogation/src/data/models/consultation_res.dart';

import '../../../../base/utils/logger.dart';
import '../../../../data/models/doctor_list_res.dart';
import '../../../../main_service.dart';

class DoctorController extends GetxController {
  //TODO: Implement DoctorController
  FocusNode focusNode = FocusNode();
  final count = 0.obs;

  TextEditingController textController = TextEditingController();
  var list = [].obs;

  ///refresh
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  int num = 0;
  int page = 1;
  int pageSize = 20;

  Future<void> onRefresh() async {
    try {
      page = 1;
      EasyLoading.show(status: 'loading...');
      List<DoctorModel>? _list = await Api.getDoctorList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value = [..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishRefresh();
      refreshController.resetFooter();
      EasyLoading.dismiss();
    }
  }

  Future<void> onLoad() async {
    try {
      page++;
      EasyLoading.show(status: 'loading...');
      List<DoctorModel>? _list = await Api.getDoctorList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value =[  ...list.value, ..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishLoad(
          num >= 20 ? IndicatorResult.noMore : IndicatorResult.success);
      EasyLoading.dismiss();
    }
  }

  @override
  void onInit() {
    super.onInit();
    onRefresh();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void postConsultation(int id,DoctorModel model) async {
    var params = Consultation(
      pid: Get.find<MainService>().userId,
      did: id,
      status: true,
      rating: 0
    );
    try {
      ConsultationRes? res = await Api.postConsultation(params);
      if (res!=null) {
        BrnToast.show("咨询成功", Get.context as BuildContext);
        Get.offAndToNamed(Routes.CHAT_DETAIL_PAGE, arguments: {
          "cid":res.data?.id??0,
          "avatar": model.photo,
          "receiverId": model.userId,
          "receiverName": model.nickName
        });
      }
    } catch (e) {
      loggy.error(e.toString());
    }
  }
}
